package cn.topevery.garden.dal.logic;

import cn.topevery.garden.dal.dao.PlaneDao;
import cn.topevery.garden.dal.dao.impl.ChangeLogDaoImpl;
import cn.topevery.garden.dal.dao.impl.PlaneDaoImpl;
import cn.topevery.garden.dal.dao.impl.PlaneUseMaterialDaoImpl;
import cn.topevery.garden.dal.dao.impl.ScheduleFileDaoImpl;
import cn.topevery.garden.dal.util.ArrayListUtils;
import cn.topevery.garden.entity.enums.PlaneExmainState;
import cn.topevery.garden.entity.po.Plane;
import cn.topevery.garden.entity.po.PlaneUseMaterial;
import cn.topevery.garden.entity.po.ScheduleFile;
import cn.topevery.garden.entity.query.PlaneQuery;
import cn.topevery.garden.entity.vo.PlaneVO;
import cn.topevery.garden.framework.base.BaseLogic;
import hw.topevery.framework.db.base.BaseEntityDao;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.entity.KeyValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 
 *
 * @author code-generate
 * @date 2022-01-24
 */
@Service
public class PlaneLogic extends BaseLogic<Plane> {
    @Autowired
    PlaneDao planeDao;

    @Autowired
    PlaneDaoImpl planeDaoImpl;

    @Autowired
    ScheduleFileDaoImpl scheduleFileMapper;

    @Autowired
    PlaneUseMaterialDaoImpl planeUseMaterialMapper;

    @Autowired
    ChangeLogDaoImpl changeLogMapper;

    @Override
    public BaseEntityDao<Plane, Integer> getDao() {
        return planeDao;
    }

    

    /**
     * 获取列表
     *
     * @param query
     */
    public DataPager<PlaneVO> listPage(PlaneQuery query) {
        return planeDao.listPage(query);
    }

    /**
     * 根据自增id批量删除
     *
     * @param ids
     */
    public void deleteBatchById(String userId,Integer[] ids) {
        planeDao.delete(userId, ids);
    }

    /**
     * 根据自增id保存或者更新
     *
     * @param plane 实体
     */
    public void saveOrUpdate(String userId, Plane plane){
        planeDao.saveOrUpdate(userId,plane);
    }

    /**
         * 根据自定义列值来获取对象
         */
    public Plane getEntityByColumn(String key, String value) {
        return planeDao.getEntityByColumn(key, value);
    }

    public Plane getEntity(String planeId) {

        Plane plane= planeDao.getEntityByColumn("c_plane_id",planeId);

        if (plane != null) {
            //附件
            List<ScheduleFile> attaches = scheduleFileMapper.getListEntityByColumns(
                    new ArrayListUtils<KeyValue>().addObject(new KeyValue("c_guid_id",planeId))
                                                 .addObject(new KeyValue("c_db_status",0)));
            plane.setAttaches(attaches);

            //详细
            List<PlaneUseMaterial> materials = planeUseMaterialMapper.getPlaneMaterials(planeId);
            plane.setMaterials(materials);
            //日志
            List<Map<String, Object>> logs = changeLogMapper.getLogByObjId(plane.getId());
            plane.setLogs(logs);
        }

        return plane;
    }

    public Map<String, Object> info(String planeId, String isVerify, String isCheck){
        List<Map<String, Object>> sta = null;
        Plane plane = this.getEntity(planeId);

        if (plane.getPlaneType() == 1) {
            sta = planeUseMaterialMapper.getMeasureSta(planeId);
        } else if (plane.getPlaneType() == 2) {
            sta = planeUseMaterialMapper.getSeedlingSta(planeId);
        }
        Map<String, Object> res = new HashMap<>();
        if (("1").equals(isVerify)) {
            plane.getMaterials().forEach(a -> {
                a.setPassAmount(a.getPlanAmount());
            });
        }
        if (("1").equals(isCheck)) {
            plane.getMaterials().forEach(a -> {
                a.setObjAmount(a.getPassAmount());
            });
        }
        res.put("plane", plane);//计划对象
        res.put("sta", sta);//统计对象
        return res;
    }

    public void insertList(String userId, Plane plane, List<PlaneUseMaterial> materials) {
        double budget = 0;
        for (PlaneUseMaterial m : materials) {
            budget += (m.getUnitPrice() * m.getMeasure() * m.getMeasureUnit());
            m.setPlaneUseMaterialGuid(UUID.randomUUID().toString());
            m.setPlaneId(plane.getPlaneId());
            m.setPlanAmount(m.getMeasure() * m.getMeasureUnit());
            m.setBudget(m.getMeasure() * m.getMeasureUnit() * m.getUnitPrice());
            m.setDbStatus(false);

            planeUseMaterialMapper.insert(userId,m);
        }
        plane.setBudget(budget);
        planeDao.insert(userId,plane);
    }

    public String submitPlane(String planeIds, String userId) {
        String[] planeId_array = planeIds.split(",");
        int successCnt = 0;
        int failedCnt = 0;
        for (String id : planeId_array) {
            int planeId = Integer.parseInt(id);
            Plane plane = planeDaoImpl.getEntityByOneColumn(new KeyValue("c_id",planeId));

            PlaneExmainState toState = null;
            if (plane.getExmainState() == PlaneExmainState.notSubmitted.getIndex()) {
                String changeName = getChangeName(plane.getPlaneName(), plane.getPlaneType());
                if (plane.getPlaneType() == 0) {
                    toState = PlaneExmainState.notVerified;
                } else {
                    toState = PlaneExmainState.toBeReviewed;
                }
//                LogStatusChange(planeId, userId, PlaneExmainState.notSubmitted.getLabel(), toState.getLabel(), changeName);

                plane.setSubmitDate(LocalDateTime.now());
                plane.setExmainState(toState.getIndex());
                plane.setExmainStateDesc(toState.getLabel());
                planeDao.update(userId,plane);

                successCnt++;
            } else {
                failedCnt++;
            }
        }
        return "成功提交了" + successCnt + "条," + "失败了" + failedCnt + "条(已提交的计划无法重复提交)";
    }

    private String getChangeName(String planeName, int planeType) {
        String changeName = "";
        switch (planeType) {
            case 0:
                changeName = "”用水计划-" + planeName + "“状态";
                break;
            case 1:
                changeName = "”用肥计划-" + planeName + "“状态";

                break;
            case 2:
                changeName = "”苗木计划-" + planeName + "“状态";

                break;
        }
        return changeName;
    }

}
